package com.superitem.school.controller;

import com.superitem.school.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("uploads")
public class FileController {
    @RequestMapping("/uploadFiles")
    public String toUpload(){
        return "upload/uploadfiles";
    }
    @RequestMapping("/startUpload")
    public String startUpload(@RequestParam("myFile") MultipartFile file, Model model){
        if(file.isEmpty()){
            new RuntimeException("未找到文件");
        }
        //获取原始的文件名
        String fileName = file.getOriginalFilename();
        //获取后缀
        String suffixName = StringUtil.getSuffixName(fileName);
        System.out.println("后缀名："+suffixName);
        //产生随机字符
        String newFileName = StringUtil.randomFileName();
        System.out.println("随机字符串名字："+newFileName);
        //确定存储位置
        String path = "D://tmp//";

        //拼接绝对名称
        String uploadPathName = path+newFileName+suffixName;

        //判断路径是否存在
        File dest = new File(uploadPathName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            //通过MultipartFile  进行上传
            file.transferTo(dest);
            model.addAttribute("fileName", "/templates/tmp/" +newFileName+suffixName);
            return "upload/showFile";
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }
}